<?php


namespace App\Http\Rest\Information\Resource;

use App\Exceptions\BusinessException;
use App\Foundation\OssAssistant;
use Framework\Facade\ConfigFacade;
use Framework\Foundation\Request\ServerRequest;
use Framework\Foundation\Response\ResponseGen;

class UploadImage
{
    /**
     * @param array $restParams
     * @param $request ServerRequest
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Envms\FluentPDO\Exception
     */
    public function getList(array $restParams, ServerRequest $request)
    {
    }

    public function getInfo(array $restParams)
    {
    }

    /**
     * @param array $restParams
     * @param $request ServerRequest
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Envms\FluentPDO\Exception
     */
    public function add(array $restParams, ServerRequest $request)
    {
        /**
         * @var $files \GuzzleHttp\Psr7\UploadedFile[];
         */
        $files = $request->getUploadedFiles();

        $memberId = $request->getAttribute('member_id', 0);
        if (!$memberId) {
            throw new BusinessException("未授权的上传");
        }
        $newNames = [];

        $conf = ConfigFacade::get('app', 'aliyun');
        $oss = new OssAssistant($conf['AccessKey']['id'], $conf['AccessKey']['secret'], $conf['oss_user_upload']['endpoint'], $conf['oss_user_upload']['bucket']);
        foreach ($files as $key => $file) {
            $realname = $memberId . '_' . time() . '_' . $files['file']->getClientFilename();
//            $name = "/uploads/information/" . $realname;
//            $filePath = ROOT . '/public' . $name;
//            $file->moveTo($filePath);
            $path = $oss->putObject($realname, $file->getStream()->getContents());

            $newNames[$key] = $path;
        }

        return ResponseGen::success($newNames);
    }


    public function edit(array $restParams, $request)
    {
    }


    public function delete(array $restParams)
    {
    }
}
